package com.LGF.Book.action;

import com.LGF.Book.bean.Member;
import com.LGF.Book.bean.MemberType;
import com.LGF.Book.bean.Record;
import com.LGF.Book.bean.Vo;
import com.LGF.Book.biz.MemberTypeBiz;
import com.LGF.Book.biz.MemberBiz;
import com.LGF.Book.biz.RecordBiz;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import sun.security.timestamp.HttpTimestamper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/member.let")
public class MemberServlet extends HttpServlet {

    MemberBiz memberBiz = new MemberBiz();
    MemberTypeBiz memberTypeBiz = new MemberTypeBiz();
    RecordBiz recordBiz = new RecordBiz();



    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    /**
     * /member.let?type=login 1:管理员页面 2：用户页面
     * /member.let?type=registerpre 进入会员注册页面准备
     * /member.let?type=register 会员注册页面
     * /member.let?type=modifypwd 管理员页面修改密码
     * /member.let?type=mem_modifypwd 会员页面修改密码
     * /member.let?type=exit 安全退出
     * /member.let?type=addpre 开卡前准备
     * /member.let?type=add  会员开卡
     * /member.let?type=query 查询所有信息
     * /member.let?type=mem_modifypre&Id=xx 修改前准备
     * /member.let?type=mem_modify 修改会员信息
     * /member.let?type=mem_remove&id=xx 删除会员信息
     * /member.let?type=ConditionSelect 条件查询
     * /member.let?type=VerifyId  验证卡号是否存在
     * /member.let?type=Rechange 充值金额
     * /member.let?type=doajax&memId=xx //用ajax异步请求传递数据搜索会员信息
     * /member.let?type=PIMpr&memId=xx //个人信息页面准备
     * /member.let?type=PIM&memId=xx //个人信息页面修改
     * /member.let?type=forgetPwd //忘记密码修改页面
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        //创建输出流对象,打印信息
        PrintWriter out = resp.getWriter();

        //创建session对象
        HttpSession session = req.getSession();
        //判断用户请求类型
        String type = req.getParameter("type");

        switch (type) {
            case "login":
                login(req, resp, out);
                break;
            case"registerpre":
                //获取所有的会员类型
                List<MemberType> memberType = memberTypeBiz.getAll();
                //存入request
                req.setAttribute("memberTypes", memberType);
                System.out.println(memberType.toString());
                //转发
                req.getRequestDispatcher("mem_register.jsp").forward(req, resp);
                break;
            case "register":
                register(req, resp, out);
                break;

            case "exit":
//                //验证用户是否登录
//                if (session.getAttribute("member") == null) {
//                    out.println("<script>alert('请登录');parent.location.href='login.jsp';</script>");
//                }
                //1.清楚session
                session.invalidate();

                //2.跳转到login.html（框架中需要回去）top.jsp->parent->index.jsp
                out.println("<script>parent.location.href='login.jsp'</script>");
                break;

            case "modifypwd":
                modifypwd(req, resp, out);
                break;

            case "addpre":
                //获取所有的会员类型
                List<MemberType> memberTypes = memberTypeBiz.getAll();
                //存入request
                req.setAttribute("memberTypes", memberTypes);
                System.out.println(memberTypes.toString());
                //转发
                req.getRequestDispatcher("mem_add.jsp").forward(req, resp);
                break;

            case "add":
                add(req, resp, out);
                break;

            case "query":
                query(req, resp, out);
                break;

            case "mem_modifypre":
                //member.let?type=mem_modifypre&Id=xx
                mem_modifypre(req, resp, out);
                break;

            case "mem_modify":
                mem_modify(req, resp, out);
                break;
            case "mem_remove":
                //member.let?type=mem_remove&id=xx 删除会员信息
                mem_remove(req, resp, out);
                break;
            case "ConditionSelect":
                //member.let?type=ConditionSelect 条件查询
                ConditionSelect(req, resp, out);
                break;
            case "VerifyId":
                //member.let?type=VerifyId  验证卡号是否存在
                VerifyId(req, resp, out);
                break;
            case "Rechange":
                //member.let?type=Rechange 充值金额
                Rechange(req, resp, out);

            case"doajax":
                doajax(req,resp,out);
                break;
            case"PIMpre":
                PIMpre(req,resp,out);
                break;
            case "PIM":
                PIM(req,resp,out);
                break;
            case "forgetPwd":
                forgetPwd(req,resp,out);
                break;
            case "mem_modifypwd":
                mem_modifypwd(req,resp,out);
                break;

            default:
                resp.sendError(404,"请求的地址不存在");
                break;

        }
    }

    /**
     * 实现会员页面修改密码功能
     * @param req
     * @param resp
     * @param out
     */
    private void mem_modifypwd(HttpServletRequest req, HttpServletResponse resp, PrintWriter out) {
        //创建session对象
        HttpSession session = req.getSession();
        //验证用户是否登录
        if (session.getAttribute("mem") == null) {
            out.println("<script>alert('请登录');location.href='login.jsp';</script>");
        }
        //获取输入的原密码 和新密码
        String pwd1 = req.getParameter("pwd");
        String newpwd = req.getParameter("newpwd");

        System.out.println(newpwd + "++++" + pwd1);

        //获取会员Id 和 会员密码
        long memberId = ((Member) session.getAttribute("mem")).getId();
        String pwd2 = ((Member) session.getAttribute("mem")).getPwd();

        System.out.println(memberId + "++++" + pwd2);

        if (pwd1.equals(pwd2)) {
            //调用biz层方法
            int count = memberBiz.modify(memberId, newpwd);
            System.out.println(count);
            if (count > 0) {
                out.println("<script>alert('密码修改成功');parent.window.location='login.jsp'</script>");
            } else {
                out.println("<script>alert('密码修改失败');parent.window.location='user_Main.jsp'</script>");
            }
        } else {
            out.println("<script>alert('原密码输入有误！');parent.window.location='admin_Main.jsp'</script>");
        }
    }

    /**
     * 实现忘记密码修改密码功能
     * @param req
     * @param resp
     * @param out
     */
    private void forgetPwd(HttpServletRequest req, HttpServletResponse resp, PrintWriter out) {
        //接收前端传过来的值
        long memId = Long.parseLong(req.getParameter("id"));
        String newpwd =req.getParameter("newpwd");

        //调用biz层 根据会员Id修改密码
        int count = memberBiz.modify(memId, newpwd);
        if (count>0){
            out.println("<script>alert('密码修改成功！');parent.window.location='login.jsp'</script>");
        }else {
            out.println("<script>alert('密码修改失败！');parent.window.location='login.jsp'</script>");

        }
    }

    /**
     * 实现会员页面 个人信息的修改
     * @param req
     * @param resp
     * @param out
     */
    private void PIM(HttpServletRequest req, HttpServletResponse resp, PrintWriter out) {
        //接收前端传过来的值memId值
        long memId = Long.parseLong(req.getParameter("memId"));

        String mname = req.getParameter("mname");
        String sex = req.getParameter("sex");
        String tel = req.getParameter("tel");
        String idNumber = req.getParameter("idNumber");

        //调用biz层修改会员信息
        int count = memberBiz.mem_modify(memId, mname, sex, tel, idNumber);
        //判断是否修改成功
        if (count>0){
            //修改成功
            out.println("<script>alert('个人信息修改成功！请重新登录');parent.window.location='login.jsp'</script>");
        }else {
            out.println("<script>alert('个人信息修改失败！');parent.window.location='user_Main.jsp'</script>");

        }


        //调用biz方法修改会员信息


    }

    /**
     * 会员个人信息 显示页面准备
     * @param req
     * @param resp
     * @param out
     */
    private void PIMpre(HttpServletRequest req, HttpServletResponse resp, PrintWriter out) throws ServletException, IOException {
        //接收前端穿过来的memId值
        long memId = Long.parseLong(req.getParameter("memId"));
        //调用biz层 根据memId查询会员信息
        Member member = memberBiz.getById(memId);
        //判断会员对象是否有值
        if (member!=null){
            //存入session中
            HttpSession session = req.getSession();
            session.setAttribute("memPIM",member);
            //调用biz层获取所有会员类型
            List<MemberType> Types = memberTypeBiz.getAll();
            System.out.println(member);
            System.out.println(Types);
            req.setAttribute("Types", Types);

            //转发
            req.getRequestDispatcher("mem_PIM.jsp").forward(req,resp);
        }
    }

    /**
     * 实现会员注册功能
     * @param req
     * @param resp
     * @param out
     */
    private void register(HttpServletRequest req, HttpServletResponse resp, PrintWriter out) {
        String pwd = req.getParameter("password");
        String sex = req.getParameter("sex");
        long memberType = Long.parseLong(req.getParameter("memberType"));
        long balance = Long.parseLong(req.getParameter("balance"));
        String mname = req.getParameter("mname");
        String tel = req.getParameter("tel");
        String idNumber = req.getParameter("idNumber");

        //进行卡号判断
        //调用biz层根据id查询会员信息
//        Member member = memberBiz.getById(memberId2);
        //进行判断是否卡号存在
            //调用biz层
            int count = memberBiz.register( mname, pwd, sex, memberType, balance, tel, idNumber);
            if (count > 0) {
                //注册成功第一次登陆进入主页面
                //调用biz层
                Member member = memberBiz.getMember(mname, pwd, idNumber);
                long memId = member.getId();
                System.out.println(member.getId());
                HttpSession session = req.getSession();
                session.setAttribute("member",member);
                out.println("<script>alert('会员注册成功,您的卡号为："+memId+"');parent.window.location='login.jsp'</script>");
            } else {
                out.println("<script>alert('会员注册失败');parent.window.location='login.jsp'</script>");
            }



    }

    /**
     * 用ajax传递会员信息
     * @param req
     * @param resp
     * @param out
     */
    private void doajax(HttpServletRequest req, HttpServletResponse resp, PrintWriter out) {
        //获取前端传过来的memId值
        long memId = Long.parseLong(req.getParameter("memId"));

        System.out.println(memId);

        //根据memId获取会员对象信息
        Member member = memberBiz.getById(memId);

        if (member!=null){
            //调用recordbiz层根据会员Id 查询会员的记录信息
            List<Record> records = recordBiz.getRecordByMemberId(member.getId());

            System.out.println(member);
            //进行判断会员是否借过书 是的话可借数量减少，没有借保持不变
            if (records.size()>0){
                //说明借过书籍 可借数量 - 记录的条数
                long size = member.getType().getAmount() - records.size();
                System.out.println(size);
                //重新设置可借数量
                member.getType().setAmount(size);
            }

            //把member对象 转给json字符串 传给前端
            String json = JSON.toJSONString(member);


            System.out.println(json);

            //打印
            out.print(json);
        }
        else{
            //转发
            out.print("false");
        }




    }

    /**
     * 实现卡号充值金额功能
     *
     * @param req
     * @param resp
     * @param out
     */
    private void Rechange(HttpServletRequest req, HttpServletResponse resp, PrintWriter out) throws ServletException, IOException {
        //获取后台传递的 卡号 和充值金额数
        long memId = Long.parseLong(req.getParameter("memId"));
        double rechange = Double.parseDouble(req.getParameter("rechange"));
        //调用biz层根据id获取会员信息
        int count = memberBiz.modifyBalance(memId, rechange);
        if (count >0) {
            //转发
            out.println("<script>alert('会员充值成功');parent.window.location='admin_Main.jsp';</script>");

        }
        else {
            out.println("<script>alert('输入信息有误请重新输入');location.href='mem_rechange.jsp';</script>");
        }


    }

    /**
     * 实现验证卡号是否存在
     *
     * @param req
     * @param resp
     * @param out
     */
    private void VerifyId(HttpServletRequest req, HttpServletResponse resp, PrintWriter out) {
        //接收前端卡号
        long memId = Long.parseLong(req.getParameter("id"));
        Member member = memberBiz.getById(memId);

        System.out.println(member);
        //转成json数据
        JSONObject json = new JSONObject();
        json.put("data",member);
        json.put("code",0);

        //打印
        out.print(json);


    }

    /**
     * 实现条件查询
     *
     * @param req
     * @param resp
     * @param out
     */
    private void ConditionSelect(HttpServletRequest req, HttpServletResponse resp, PrintWriter out) {

        //获取前台传过来搜索条件
        String searchType = req.getParameter("searchType");
        if (searchType.equals("mname")) {
            //获取前台传过来的输入框的值
            String mname = req.getParameter("search");
            //调用biz层方法模糊查询
            List<Member> members = memberBiz.selectByMname(mname);
            System.out.println(members);
            //转成json数据
            JSONObject json = new JSONObject();
            json.put("data", members);
            json.put("code", 0);
            json.put("count", members.size());
            out.print(json);


        } else if (searchType.equals("memId")) {
            //获取前台传过来的输入框的值
            String memId = req.getParameter("search");
            System.out.println(memId);
            //调用biz层方法模糊查询数据
            List<Member> members = memberBiz.selectById(memId);
            System.out.println(members);
            //转成json数据
            JSONObject json = new JSONObject();
            json.put("data", members);
            json.put("code", 0);
            json.put("count", members.size());
            out.print(json);
        } else {
            out.println("alert('搜索失败');location.href='mem_list.jsp'");
        }


    }


    /**
     * 删除会员信息功能
     *
     * @param req
     * @param resp
     * @param out
     */
    private void mem_remove(HttpServletRequest req, HttpServletResponse resp, PrintWriter out) {
        //获取传递过来的id
        long memId = Long.parseLong(req.getParameter("id"));
        //调用biz层根据id删除会员方法
        int count = memberBiz.mem_remove(memId);
        if (count > 0) {
            out.println("<script>alert('删除会员成功');location.href='mem_list.jsp';</script>");
        } else {
            out.println("<script>alert('删除会员失败');location.href='mem_list.jsp';</script>");

        }


    }

    /**
     * 实现用户登录功能
     *
     * @param req
     * @param resp
     * @param out
     */
    private void login(HttpServletRequest req, HttpServletResponse resp, PrintWriter out) {
        //创建session对象
        HttpSession session = req.getSession();
        //获取验证码
        String usercode = req.getParameter("code");
        //提取session中的验证码，进行判断
        String code = session.getAttribute("code").toString();
        //判断验证是否相等 不区分大小写
        if (!code.equalsIgnoreCase(usercode)) {
            out.println("<script>alert('验证码输入错误');location.href='login.jsp';</script>");
            return;
        }
        //获取前端传过来的值
        long id = Long.parseLong(req.getParameter("id"));
        String pwd = req.getParameter("pwd");
        long power = Long.parseLong(req.getParameter("power"));
        //调用memberbiz层的方法根据编号，密码，用户类型编号获取会员对象
        Member member = memberBiz.getMember(id, pwd, power);
        if (member == null) {
            out.println("<script>alert('用户名或密码不存在');location.href='login.jsp';</script>");
        } else {
            if (power == 1) {
                //进入管理员页面
                HttpSession admin = req.getSession();
                admin.setAttribute("member", member);
                List<Record> recordList = recordBiz.getAllMemId(member.getId());
                session.setAttribute("recordList",recordList);
                out.println("<script>alert('登录成功');location.href='admin_Main.jsp';</script>");
            } else if (power == 2) {
                //进入用户主页面
                HttpSession session1 = req.getSession();
                session1.setAttribute("mem", member);
                List<Record> recordList = recordBiz.getAllMemId(member.getId());
                session.setAttribute("recordList",recordList);
                out.println("<script>alert('登录成功');location.href='user_Main.jsp';</script>");
            } else {
                out.println("404");
            }
        }
    }

    /**
     * 修改会员密码功能
     *
     * @param req
     * @param resp
     * @param out
     */
    private void modifypwd(HttpServletRequest req, HttpServletResponse resp, PrintWriter out) {
        //创建session对象
        HttpSession session = req.getSession();
        //验证用户是否登录
//        if (session.getAttribute("member") == null) {
//            out.println("<script>alert('请登录');location.href='login.jsp';</script>");
//        }
        //获取输入的原密码 和新密码
        String pwd1 = req.getParameter("pwd");
        String newpwd = req.getParameter("newpwd");

        System.out.println(newpwd + "++++" + pwd1);

        //获取会员Id 和 会员密码
        long memberId = ((Member) session.getAttribute("member")).getId();
        String pwd2 = ((Member) session.getAttribute("member")).getPwd();

        System.out.println(memberId + "++++" + pwd2);

        if (pwd1.equals(pwd2)) {
            //调用biz层方法
            int count = memberBiz.modify(memberId, newpwd);
            System.out.println(count);
            if (count > 0) {
                out.println("<script>alert('密码修改成功');parent.window.location='login.jsp'</script>");
            } else {
                out.println("<script>alert('密码修改失败');parent.window.location='admin_Main.jsp'</script>");
            }
        } else {
            out.println("<script>alert('原密码输入有误！');parent.window.location='admin_Main.jsp'</script>");
        }
    }

    /**
     * 添加会员信息
     *
     * @param req
     * @param resp
     * @param out
     */
    private void add(HttpServletRequest req, HttpServletResponse resp, PrintWriter out) {

        long memberId2 = Long.parseLong(req.getParameter("id"));
        String password = req.getParameter("password");
        String sex = req.getParameter("sex");
        long memberType = Long.parseLong(req.getParameter("memberType"));
        long balance = Long.parseLong(req.getParameter("balance"));
        String mname = req.getParameter("mname");
        String tel = req.getParameter("tel");
        String idNumber = req.getParameter("idNumber");

        //进行卡号判断
        //调用biz层根据id查询会员信息
        Member member = memberBiz.getById(memberId2);
        //进行判断是否卡号存在
        if (member!=null){
            out.println("<script>alert('会员卡号已存在请重新填写会员信息');window.location='member.let?type=addpre'</script>");

        }else {

            //调用biz层
            int count = memberBiz.add(memberId2, mname, password, sex, memberType, balance, tel, idNumber);
            if (count > 0) {
                out.println("<script>alert('会员开卡成功');parent.window.location='admin_Main.jsp'</script>");
            } else {
                out.println("<script>alert('会员开卡失败');parent.window.location='admin_Main.jsp'</script>");
            }

        }


    }

    /**
     * 查询会员列表信息 提供分页功能
     *
     * @param req
     * @param resp
     * @param out
     */
    private void query(HttpServletRequest req, HttpServletResponse resp, PrintWriter out) {
        //member.let?type=query&page=1&limit=10
        int page = Integer.parseInt(req.getParameter("page"));
        int limit = Integer.parseInt(req.getParameter("limit"));
        //System.out.println(page);
        //System.out.println(limit);
        int pageIndex = (page - 1) * limit;
        //调用biz层方法获取分页后的会员数
        List<Member> memberList = memberBiz.getByPage(pageIndex, limit);
        System.out.println(memberList);
        //获取所有会员数
        List<Member> all = memberBiz.getAll();

        //转成json数据
        JSONObject json = new JSONObject();
        json.put("data", memberList);
        json.put("code", 0);
        json.put("count", all.size());
        out.print(json);
        //查询全部
        //List<Member> memberList = memberBiz.getAll();
    }

    /**
     * 修改会员前准备工作 跳转mem_modify.jsp
     *
     * @param req
     * @param resp
     * @param out
     */
    private void mem_modifypre(HttpServletRequest req, HttpServletResponse resp, PrintWriter out) throws ServletException, IOException {
        //接收会员编号
        long memId = Long.parseLong(req.getParameter("Id"));
        System.out.println(memId);
        //调用biz层根据id查询会员信息
        Member member = memberBiz.getById(memId);
        //调用biz层获取所有会员类型
        List<MemberType> memberTypes = memberTypeBiz.getAll();
        System.out.println(member);
        System.out.println(memberTypes);
        //存储session对象
        req.setAttribute("member", member);
        req.setAttribute("memberTypes", memberTypes);
        //转发
        req.getRequestDispatcher("mem_modify.jsp").forward(req, resp);

    }

    /**
     * 修改会员信息
     *
     * @param req
     * @param resp
     * @param out
     */
    private void mem_modify(HttpServletRequest req, HttpServletResponse resp, PrintWriter out) {

        //获取修改页面的所有参数
        long memId = Long.parseLong(req.getParameter("id"));
        String mname = req.getParameter("mname");
        String sex = req.getParameter("sex");
        String pwd = req.getParameter("pwd");
        long mtId = Long.parseLong(req.getParameter("mtname"));
        double balance = Double.parseDouble(req.getParameter("balance"));
        String tel = req.getParameter("tel");
        String idNumber = req.getParameter("idNumber");

        //调用biz层修改会员信息方法 返回int
        int count = memberBiz.mem_modify(memId, mname, pwd, sex, mtId, balance, tel, idNumber);
        System.out.println(count);
        if (count > 0) {
            out.println("<script>alert('会员修改信息成功');location.href='mem_list.jsp'</script>");

        } else {
            out.println("<script>alert('会员修改信息失败');location.href='mem_list.jsp'</script>");

        }


    }
}
